package com.ai.file;

import com.alibaba.fastjson2.JSONObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class Iamge2Base64T {
    public static void main(String[] args) throws IOException {
       extracted();

    }

    private static void extracted() {
        String BASE = "C:\\Users\\14550\\Pictures\\";
        // 读取图片文件

        List<String> base64ImageList = new ArrayList<>();
       // extracted(BASE, base64ImageList,"base64_1.jpg");
        extracted(BASE, base64ImageList,"tz.jpg");
       // extracted(BASE, base64ImageList,"loadCookie.png");
        System.out.println(JSONObject.toJSONString(base64ImageList));
        //base2Image(encodedImage,BASE+"base64_2.jpg");

    }

    private static void extracted(String BASE, List<String> base64ImageList,String fileName) {
        File imageFile = new File(BASE +fileName);
        file2Base64(imageFile, base64ImageList);
    }

    private static void file2Base64(File imageFile ,   List<String> base64ImageList) {
        try (InputStream inputStream = new FileInputStream(imageFile)) {
            byte[] buffer = new byte[inputStream.available()];
            // 将输入流内容存入字节数组buffer
            int bytesRead = inputStream.read(buffer);
            if (bytesRead != -1) {
                // 创建Base64对象并进行编码
                String imageBase64Str = Base64.getEncoder().encodeToString(buffer);

                base64ImageList.add("data:image/png;base64,"+imageBase64Str);
            } else {
                System.err.println("无法读取图像文件！");
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public static void base2Image(String base64String, String imageFileName) {
        ByteArrayInputStream bais = null;
        try {
            //获取图片类型
            String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            //获取JDK8里的解码器Base64.Decoder,将base64字符串转为字节数组
            byte[] bytes = Base64.getDecoder().decode(base64String);
            //构建字节数组输入流
            bais = new ByteArrayInputStream(bytes);
            //通过ImageIO把字节数组输入流转为BufferedImage
            BufferedImage bufferedImage = ImageIO.read(bais);
            //构建文件
            File imageFile = new File(imageFileName);
            //写入生成文件
            ImageIO.write(bufferedImage, suffix, imageFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bais != null) {
                    bais.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
